package valerij_timakov.home_finances.conf;
//import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import valerij_timakov.home_finances.exceptions.AppSystemException;

public class Conf {
	
	public static final String CONF_PATH_PROPERTY_NAME = "project.bens.conf.path";
	private static final String CONF_RES_FILE_NAME = "beans.xml";
//	private static final Logger logger = Logger.getLogger(Conf.class);
	private static Conf instance;
	
	static {
		instance = new Conf();
		try {
			instance.bootstrap();
		} catch (AppSystemException e) {
			throw new Error(e);
		}
	}
	
	private ConfigurableApplicationContext ctx;
	
	private Conf() {
		super();
	}
	
	public static Conf getInstance() {
		return instance;
	}
	
	public <T> T getBean(String beanName, Class<T> classType) {
		return ctx.getBean(beanName, classType);
	}
	
	public <T> T getBean(Class<T> classType) {
		String beanName = classType.getSimpleName();
		beanName = beanName.substring(0, 1).toLowerCase() + beanName.substring(1);
		return ctx.getBean(beanName, classType);
	}
	
	private void bootstrap() throws AppSystemException {
		String confPath = System.getProperty(CONF_PATH_PROPERTY_NAME);	
		if (confPath != null && !confPath.isEmpty()) {
			try {
				ctx = new FileSystemXmlApplicationContext(confPath);
			} catch (BeansException e) {
				throw new AppSystemException("Ошибка загрузки контекста!", e);
			}
		} else {
			try {
				ctx = new ClassPathXmlApplicationContext(CONF_RES_FILE_NAME);
			} catch (BeansException e) {
				throw new AppSystemException("Ошибка загрузки контекста!", e);
			}
		}
		if (ctx == null || !ctx.isActive()) {
			throw new AppSystemException("Ошибка загрузки контекста!");
		}
	}
}
